package com.controller;

import com.alibaba.druid.support.json.JSONParser;
import com.dto.excution.ListExcution;
import com.dto.in.MapDto;
import com.entity.*;
import com.enums.ListEnum;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.service.SelectFormService;

import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.ir.debug.JSONWriter;
import org.apache.commons.collections.map.HashedMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;
import sun.misc.BASE64Decoder;


import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018/10/20.
 */
@RestController
@RequestMapping("selectForm")
public class SelectFormController {
    @Autowired
    private SelectFormService selectFormService;


    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @ApiOperation(value = "查课程表")
    @PostMapping(value = "/subject")
    @ResponseBody
    public ListExcution<List<Subject>> subjectList() {
        List<Subject> res = selectFormService.subjectList();
        if (res != null)
            return new ListExcution<List<Subject>>(res, ListEnum.SUCCESS);
        else return new ListExcution<List<Subject>>(res, ListEnum.FAIL);
    }

    @ApiOperation(value = "查地区表")
    @PostMapping(value = "/location")
    @ResponseBody
    public ListExcution<List<Location>> locationList(String cityName) {
        List<Location> res = selectFormService.locationList(cityName);
        if (res != null)
            return new ListExcution<List<Location>>(res, ListEnum.SUCCESS);
        else return new ListExcution<List<Location>>(res, ListEnum.FAIL);
    }

    @ApiOperation(value = "查地区表")
    @PostMapping(value = "/locationWhereCityId")
    @ResponseBody
    public ListExcution<List<Location>> locationWhereCityId(Integer cityId) {
        List<Location> res = selectFormService.locationWhereCityId(cityId);
        if (res != null)
            return new ListExcution<List<Location>>(res, ListEnum.SUCCESS);
        else return new ListExcution<List<Location>>(res, ListEnum.FAIL);
    }

    @ApiOperation(value = "查城市表")
    @PostMapping(value = "/city")
    @ResponseBody
    public ListExcution<List<City>> cityList() {
        List<City> res = selectFormService.cityList();
        if (res != null)
            return new ListExcution<List<City>>(res, ListEnum.SUCCESS);
        else return new ListExcution<List<City>>(res, ListEnum.FAIL);
    }

    @ApiOperation(value = "查学校表")
    @PostMapping(value = "/school")
    @ResponseBody
    public ListExcution<List<School>> schoolList(String cityName) {
        List<School> res = selectFormService.schoolList(cityName);
        if (res != null)
            return new ListExcution<List<School>>(res, ListEnum.SUCCESS);
        else return new ListExcution<List<School>>(res, ListEnum.FAIL);
    }

    @ApiOperation(value = "查专业表")
    @PostMapping(value = "/major")
    @ResponseBody
    public ListExcution<List<Major>> majorList() {
        List<Major> res = selectFormService.majorList();
        if (res != null)
            return new ListExcution<List<Major>>(res, ListEnum.SUCCESS);
        else return new ListExcution<List<Major>>(res, ListEnum.FAIL);
    }

    @ApiOperation(value = "查籍贯表")
    @PostMapping(value = "/birthPlace")
    @ResponseBody
    public ListExcution<List<BirthPlace>> birthPlaceList() {
        List<BirthPlace> res = selectFormService.birthPlaceList();
        if (res != null)
            return new ListExcution<List<BirthPlace>>(res, ListEnum.SUCCESS);
        else return new ListExcution<List<BirthPlace>>(res, ListEnum.FAIL);
    }

    @ApiOperation(value = "上传头像")
    @PostMapping(value = "/upPhoto")
    @ResponseBody
    public String upPhoto(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        System.out.println("执行upload");
        request.setCharacterEncoding("UTF-8");
        System.out.println("执行图片上传");
        String user = request.getParameter("userId");
        System.out.println("user:" + user);
        String path = null;
        String type = null;
        if (!file.isEmpty()) {
            System.out.println("成功获取照片");
            String fileName = file.getOriginalFilename();
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            System.out.println("图片初始名称为：" + fileName + " 类型为：" + type);
            if (type != null) {
                if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    String realPath = "c:/images/photo/";
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
                    // 设置存放图片文件的路径
                    path = realPath + trueFileName;
                    System.out.println("存放图片文件的路径:" + path);
                    file.transferTo(new File(path));
                    System.out.println("文件成功上传到指定目录下");
                    int i = selectFormService.upPhoto(user, "https://www.lingyingjiajiao.com/images/photo/" + trueFileName);
                    if (i == 1)
                        return "https://www.lingyingjiajiao.com/images/photo/" + trueFileName;
                    else return "false";
                } else {
                    System.out.println("不是我们想要的文件类型,请按要求重新上传");
                    return "error";
                }
            } else {
                System.out.println("文件类型为空");
                return "error";
            }
        } else {
            System.out.println("没有找到相对应的文件");
            return "error";
        }
    }

    @ApiOperation(value = "教师认证")
    @PostMapping(value = "/upImg")
    @ResponseBody
    public String upImg(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        request.setCharacterEncoding("UTF-8");
        String user = request.getParameter("userId");
        String position = request.getParameter("position");
        String path = null;
        String type = null;
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            if (type != null) {
                if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    String realPath = "c:/images/identify/";
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
                    // 设置存放图片文件的路径
                    path = realPath + trueFileName;
                    file.transferTo(new File(path));
                    int i = selectFormService.TeacherIdentify(user, "https://www.lingyingjiajiao.com/images/identify/" + trueFileName, position);
                    if (i == 1)
                        return "上传成功";
                    else return "false";
                } else {
                    System.out.println("不是我们想要的文件类型,请按要求重新上传");
                    return "error";
                }
            } else {
                System.out.println("文件类型为空");
                return "error";
            }
        } else {
            System.out.println("没有找到相对应的文件");
            return "error";
        }
    }

    @ApiOperation(value = "查询认证")
    @PostMapping(value = "/findIdentify")
    @ResponseBody
    public String findIdentify(String userId) {
        String res = selectFormService.findTeacherIdentify(userId);
        return res;
    }

    @ApiOperation(value = "查询订单状态")
    @PostMapping(value = "/findRecordStatus")
    @ResponseBody
    public String findRecordStatus(String recordStatus) {
        String res = selectFormService.findRecordStatus(recordStatus);
        return res;
    }

    @ApiOperation(value = "保存路线")
    @PostMapping(value = "/savePath")
    @ResponseBody
    public int savePath(MapDto mapDto) throws Exception {
        Integer recordId = mapDto.getRecordId();
        String thisLocation = mapDto.getThisLocation();
        String thisLat = mapDto.getThisLat();
        String thisLog = mapDto.getThisLog();
        String aimLocation = mapDto.getAimLocation();
        String aimLat = mapDto.getAimLat();
        String aimLog = mapDto.getAimLog();
        return selectFormService.savePath(recordId, thisLocation, thisLat, thisLog, aimLocation, aimLat, aimLog);
    }

    @ApiOperation(value = "查询订单是否已经预约或申请")
    @PostMapping(value = "/selectRecord")
    @ResponseBody
    public ListExcution<Void> selectRecord(Integer stdUserId, Integer stdId, Integer teaUserId, Integer teaId) {
        int res = selectFormService.selectRecord(stdUserId, stdId, teaUserId, teaId);
        if (res > 0) {
            return new ListExcution<Void>(null, ListEnum.FAIL);
        } else {
            return new ListExcution<Void>(null, ListEnum.SUCCESS);
        }
    }

    @ApiOperation(value = "查询订单是否已经预约或申请")
    @PostMapping(value = "/selectRecord2")
    @ResponseBody
    public ListExcution<Void> selectRecord2(Integer stdUserId, Integer stdId, Integer teaUserId, Integer teaId) {
        int res = selectFormService.selectRecord2(stdUserId, stdId, teaUserId, teaId);
        if (res > 0) {
            return new ListExcution<Void>(null, ListEnum.FAIL);
        } else {
            return new ListExcution<Void>(null, ListEnum.SUCCESS);
        }
    }

    @ApiOperation(value = "插入订单")
    @PostMapping(value = "/insertRecord")
    @ResponseBody
    public synchronized String insertRecord(String stdUserId, String teaUserId, String stdId, String teaId, String recordType) {
        String Rid = String.valueOf(System.currentTimeMillis());
        System.out.println(Rid);
        int res = selectFormService.insertRecord(stdUserId, teaUserId, Rid, stdId, teaId, recordType);
        if (res > 0) {
            return "操作成功";
        } else {
            return "操作失败";
        }
    }

    /**
     * get请求获取String类型数据
     *
     * @param url 请求链接
     * @return
     */
    public static String get(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        StringBuffer sb = new StringBuffer();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            System.out.println("Res:" + (entity.getContent()));
            InputStreamReader reader = new InputStreamReader(entity.getContent(), "utf-8");
            char[] charbufer;
            while (0 < reader.read(charbufer = new char[10])) {
                sb.append(charbufer);
            }
        } catch (IOException e) {//1
            e.printStackTrace();
        } finally {
            httpGet.releaseConnection();
        }
        JSONObject json = new JSONObject(sb.toString());
        String openid = (String) json.get("openid");
        return openid;
    }


    @ApiOperation(value = "获取Code")
    @PostMapping(value = "/requiredCode")
    @ResponseBody
    public String requiredCode(String code, String userId) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx1a47bb9e4089c8e2&secret=6fc9a52136015e492b033df19e6f1885&js_code=" + code + "&grant_type=authorization_code";
        //获取openID
        String openId = get(url);
        if(userId != null){
            if (openId != null) {
                int i = selectFormService.insertOpenId(userId, openId);
                if (i > 0) return "操作成功";
            }
        }else{
            return openId;
        }

        return "操作失败";
    }

    @ApiOperation(value = "发送推送")
    @PostMapping(value = "/sendMsg")
    @ResponseBody
    public String sendMsg(String userId, String formId, Integer type) {
        String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + getAccess_token();
        String openId = selectFormService.findOpenId(userId);
//        String formId = selectFormService.findFormId(userId);
        Wxmsg wxMssVo = new Wxmsg();
        wxMssVo.setTouser(openId);//用户openid
        if (type == 1) {
            wxMssVo.setTemplate_id("zGj5FKZytGMUhfXxa6iAaSL9q9rYcnaqG0NPoW5-UA8");
        } else if (type == 2) {
            wxMssVo.setTemplate_id("TkRkREMC-s7zwnkWHS1ko8H6QiuwdyC98IzkIPlZ_N0");
        } else if (type == 3) {
            wxMssVo.setTemplate_id("q8Sl6Xyg1r93nr0SS8cefY_JD4HbormNvXp4qnqK0-g");
        } else {
            wxMssVo.setTemplate_id("q8Sl6Xyg1r93nr0SS8cefY_JD4HbormNvXp4qnqK0-g");
        }
        wxMssVo.setForm_id(formId);//formid
        wxMssVo.setPage("pages/index/index");
        Map<String, TemplateData> map = null;

        Map<String, TemplateData> m = new HashMap<>(5);

        //keyword1：订单类型，keyword2：下单金额，keyword3：配送地址，keyword4：取件地址，keyword5备注
        //这里改模板的数据。
        TemplateData keyword1 = new TemplateData();
        TemplateData keyword2 = new TemplateData();
        SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = tempDate.format(new java.util.Date());

        if (type == 1) {
            keyword1.setValue("有老师申请了你");
            m.put("keyword1", keyword1);
            keyword2.setValue(time);
            m.put("keyword2", keyword2);
            wxMssVo.setData(m);
        } else if (type == 2) {
            keyword1.setValue("有学生预约了您");
            m.put("keyword1", keyword1);
            keyword2.setValue(time);
            m.put("keyword2", keyword2);
            wxMssVo.setData(m);
        } else if (type == 3) {
            keyword1.setValue("有交换电话请求");
            m.put("keyword1", keyword1);
            keyword2.setValue(time);
            m.put("keyword2", keyword2);
            wxMssVo.setData(m);
        } else if (type == 4) {
            keyword1.setValue("交换电话被同意");
            m.put("keyword1", keyword1);
            keyword2.setValue(time);
            m.put("keyword2", keyword2);
            wxMssVo.setData(m);
        } else if (type == 5) {
            keyword1.setValue("交换电话被拒绝");
            m.put("keyword1", keyword1);
            keyword2.setValue(time);
            m.put("keyword2", keyword2);
            wxMssVo.setData(m);
        }
        ResponseEntity<String> responseEntity =
                restTemplate().postForEntity(url, wxMssVo, String.class);
        System.out.println("dfa" + responseEntity.getBody());
        return responseEntity.getBody();
    }

    @ApiOperation(value = "新增formId")
    @PostMapping(value = "/insertFormId")
    @ResponseBody
    public int insertFormId(String userId, String formId) {
        if (formId == null) {
            return 0;
        } else {
            return selectFormService.insertFormId(userId, formId);
        }
    }

    @ApiOperation(value = "查询对方formId")
    @PostMapping(value = "/selectOhterFormId")
    @ResponseBody
    public List<formIdInfo> selectOhterFormId(String userId) {
        List<formIdInfo> formId = selectFormService.selectOhterFormId(userId);
        return formId;
    }


    @ApiOperation(value = "修改formId的失效时间")
    @PostMapping(value = "/updateFormId")
    @ResponseBody
    public int updateFormId(Integer id) {
        return selectFormService.updateFormId(id);
    }

    @ApiOperation(value = "查询或插入openID")
    @PostMapping(value = "/openIdOperation")
    @ResponseBody
    public String openIdOperation(String userId, String openId, String operation) {
        if (operation.equals("insert")) {
            if (openId != "") {
                int i = selectFormService.insertOpenId(userId, openId);
                if (i > 0) return "操作成功";
            } else return "openid不能为空";
        } else if (operation.equals("find")) {
            return selectFormService.findOpenId(userId);
        } else return "操作类型错误";
        return "false";
    }

    @ApiOperation(value = "取消订单")
    @PostMapping(value = "/updateRecord")
    @ResponseBody
    public String updateRecord(Integer recordId) {
        int res = selectFormService.updateRecord(recordId);
        if (res > 0) {
            return "操作成功";
        } else {
            return "操作失败";
        }
    }


    @ApiOperation(value = "查询订单")
    @PostMapping(value = "/findRecord")
    @ResponseBody
    public List<?> findRecord(String UserId, String type, int limit) {
        if (type.equals("1")) {//YY
            List<AssociationInfo> res = selectFormService.findRecordStudent(UserId, limit, "YY");
            return res;
        } else if (type.equals("2")) {//SQ
            List<AssociationInfo> res = selectFormService.findRecordStudent(UserId, limit, "SQ");
            return res;
        } else return null;
    }

    @ApiOperation(value = "查询余额")
    @PostMapping(value = "/findMoney")
    @ResponseBody
    public BigDecimal findMoney(String userId) {
        return selectFormService.findMoney(userId);
    }

    @ApiOperation(value = "充值余额")
    @PostMapping(value = "/addMoney")
    @ResponseBody
    public ListExcution<BigDecimal> addMoney(String userId, BigDecimal money) {
        BigDecimal ash = selectFormService.findMoney(userId);
        BigDecimal bigDecimal = ash.add(money);
        int i = selectFormService.addMoney(bigDecimal, userId);
        if (i > 0)
            return new ListExcution<BigDecimal>(bigDecimal, ListEnum.SUCCESS);
        else return new ListExcution<BigDecimal>(bigDecimal, ListEnum.FAIL);
    }

    @ApiOperation(value = "认证短信")
    @PostMapping(value = "/identifyMsg")
    @ResponseBody
    public String identifyMsg(String phone, String type,int types) {
        String url = "https://api.mysubmail.com/message/xsend";
        Map<String, String> map = new HashMap<String, String>();
        map.put("appid", "28633");
        map.put("to", phone);
        if (type.equals("pass")){
            if(types == 1){
                map.put("project", "I4wWT4");
            }else{
                map.put("project", "YDcnf");
            }
        }else{
            map.put("project", "fuBFD2");
        }
        map.put("signature", "a8f3a7b6a8c8c3af115a1fc84c3fd9b9");
        ResponseEntity<String> responseEntity =
                restTemplate().postForEntity(url, map, String.class);
        System.out.println("identify" + responseEntity.getBody());

        return responseEntity.getBody();
    }

    @ApiOperation(value = "网站验证码")
    @PostMapping(value = "/indexMsg")
    @ResponseBody
    public String indexMsg(String phone) {
        String url = "https://api.mysubmail.com/message/xsend";
        Map<String, String> map = new HashMap<String, String>();
        map.put("appid", "28633");
        map.put("to", phone);
        map.put("project", "yeSJs");
        map.put("signature", "a8f3a7b6a8c8c3af115a1fc84c3fd9b9");
        ResponseEntity<String> responseEntity =
                restTemplate().postForEntity(url, map, String.class);
        System.out.println("dfa" + responseEntity.getBody());

        return responseEntity.getBody();
    }

    @ApiOperation(value = "我的预约和被申请")
    @PostMapping(value = "/myAppointment")
    @ResponseBody
    public ListExcution<List<AssociationInfo>> myAppointment(Integer userId, Integer type, Integer limit) {
        List<AssociationInfo> res = selectFormService.myAppointment(userId, type, limit);
        return new ListExcution<List<AssociationInfo>>(res, ListEnum.SUCCESS);
    }

    @ApiOperation(value = "查询我的发布下的申请列表")
    @PostMapping(value = "/findMyPublishAppointment")
    @ResponseBody
    public ListExcution<List<AssociationInfo>> findMyPublishAppointment(Integer userId, Integer id, Integer limit) {
        List<AssociationInfo> res = selectFormService.findMyPublishAppointment(userId, id, limit);
        return new ListExcution<List<AssociationInfo>>(res, ListEnum.SUCCESS);
    }

    public static String getAccess_token() {
        HttpClient client;
        String apiurl = "https://api.weixin.qq.com/cgi-bin/token";
        String appId = "wx1a47bb9e4089c8e2";
        String secret = "6fc9a52136015e492b033df19e6f1885";
        String turl = String.format("%s?grant_type=client_credential&appid=%s&secret=%s", apiurl, appId, secret);
        client = new DefaultHttpClient();
        HttpGet get = new HttpGet(turl);
        JsonParser jsonparer = new JsonParser();// 初始化解析json格式的对象
        String result = null;
        try {
            HttpResponse res = client.execute(get);
            String responseContent = null; // 响应内容
            HttpEntity entity = res.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
            JsonObject json = jsonparer.parse(responseContent).getAsJsonObject();
            // 将json字符串转换为json对象
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                if (json.get("errcode") != null) {// 错误时微信会返回错误码等信息，{"errcode":40013,"errmsg":"invalid
                    // appid"}
                } else {// 正常情况下{"access_token":"ACCESS_TOKEN","expires_in":7200}
                    result = json.get("access_token").getAsString();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接 ,释放资源
            client.getConnectionManager().shutdown();
            return result;
        }
    }
}

